﻿using Microsoft.SharePoint.Client;
using System;
using System.IO;
using System.Linq;

namespace IteraProvisioning.Core
{
    /// <summary>
    /// Class that deals with site (both site collection and web site) creation, status, retrieval and settings
    /// </summary>
    public static class WebExtensions
    {
        #region Apps and sandbox solutions

        /// <summary>
        /// Check app instance exists by title
        /// </summary>
        /// <param name="web">The site to process</param>
        /// <param name="appTitle">Title of app</param>
        /// <returns>Instance of app that corresponds to particular title</returns>
        public static AppInstance GetAppInstanceByTitle(this Web web, string appTitle)
        {
            var instances = AppCatalog.GetAppInstances(web.Context, web);
            web.Context.Load(instances, i => i.Include(app => app.Title, app => app.AppWebFullUrl, app => app.StartPage));
            web.Context.ExecuteQuery();

            return Enumerable.FirstOrDefault(instances, app => string.Equals(app.Title, appTitle, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="web">The site to process</param>
        /// <param name="packageStream">Stream of app file</param>
        /// <param name="appTitle">app title</param>
        /// <returns>Instance of new or existing app</returns>
        public static AppInstance DeployApp(this Web web, MemoryStream packageStream, string appTitle)
        {
            AppInstance appInstance = web.GetAppInstanceByTitle(appTitle);
            if (appInstance == null)
            {
                appInstance = web.LoadAndInstallApp(packageStream);
                web.Context.Load(appInstance, app => app.AppWebFullUrl, app => app.StartPage, app => app.Title);
                web.Context.ExecuteQuery();
                packageStream.Close();
            }
            return appInstance;
        }



        #endregion
    }
}
